package com.cn.fangshuo.task;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cn.fangshuo.entity.CarWash;
import com.cn.fangshuo.entity.CarWashPushLog;
import com.cn.fangshuo.enums.RedisKeyEnum;
import com.cn.fangshuo.service.ICarWashPushLogService;
import com.cn.fangshuo.service.ICarWashService;
import com.cn.fangshuo.util.ImageUtil;
import com.cn.fangshuo.util.RedisUtil;
import com.cn.fangshuo.util.StrUtil;
import com.cn.fangshuo.util.TimeUtil;
import jakarta.annotation.PostConstruct;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;

@Component
@Slf4j
public class PushWuWxiCarWashTask {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private ICarWashService carWashService;

    @Autowired
    private ICarWashPushLogService carWashPushLogService;

    private final String baseURL = "https://scs.wxmetro.net:1506/prod-api";

    //key：设备号，value：key
    Map<String, String> keyMap = new HashMap<>();
    @PostConstruct
    void intiKeyMap(){
        if (keyMap.isEmpty()){
            keyMap.put("YYCC1000001420", "f74f08cd-9554-4156-85eb-fecb961e6faa");//区政府
            keyMap.put("YYCC1000001429", "b7e938e9-79af-4ac1-ae32-d1ebbc2f8593");//龙潭路
            keyMap.put("YYCC1000001478", "8fcc812a-a2d4-4776-8d8d-49bdda3b5902");//葛埭桥
        }
    }

    //key：设备号，value：secret
    Map<String, String> secretMap = new HashMap<>();
    @PostConstruct
    void intiSecretMap(){
        if (secretMap.isEmpty()){
            secretMap.put("YYCC1000001420", "dda20e6f-80b4-47e8-9e5c-394c467d76a0");//区政府
            secretMap.put("YYCC1000001429", "65dfb978-9ec3-4c5d-bdab-2dd99448d8e3");//龙潭路
            secretMap.put("YYCC1000001478", "e0f93d8a-9515-48e3-9dda-a10e55c818fe");//葛埭桥
        }
    }

    //key：设备号，value：项目编号
    Map<String, String> deviceMap = new HashMap<>();
    @PostConstruct
    void intiDeviceMap(){
        if (deviceMap.isEmpty()){
            deviceMap.put("YYCC1000001420", "HT202309130019");//区政府
            deviceMap.put("YYCC1000001429", "HT202410101605");//龙潭路
            deviceMap.put("YYCC1000001478", "HT202510090001");//葛埭桥
        }
    }

    private final Map<Integer, String> colorMap = new HashMap<>();
    @PostConstruct
    void intiColorMap(){
        if (colorMap.isEmpty()){
            colorMap.put(1, "黄");
            colorMap.put(2, "绿");
            colorMap.put(3, "白");
            colorMap.put(4, "黑");
            colorMap.put(0, "蓝");
        }
    }

    private final Map<Integer, Integer> eventMap = new HashMap<>();
    @PostConstruct
    void intiEventMap(){
        if (colorMap.isEmpty()){
            eventMap.put(2, 0);//正常冲洗
            eventMap.put(1, 1);//冲洗时长不足
            eventMap.put(0, 2);//未冲洗
            eventMap.put(3, 3);//绕行
        }
    }


    @Scheduled(fixedRate = 2 * 60 * 1000)
    public void push() {
        Set<String> deviceUuids = deviceMap.keySet();
        for (String deviceUuid : deviceMap.keySet()){
            String lastCarWashPushTime = redisUtil.getString(RedisKeyEnum.LAST_CAR_WASH_PUSH_TIME.getKey() + deviceUuid);
            LocalDateTime startTime;
            if (StrUtil.isBlank(lastCarWashPushTime)){
                startTime = LocalDateTime.now().minusMinutes(5);
            } else {
                startTime = TimeUtil.parseLocalDateTime(lastCarWashPushTime);
            }
            LocalDateTime endTime = LocalDateTime.now();
            //这个厂商只接受黄牌车的冲洗记录
            List<CarWash> carWashList = carWashService.list(new LambdaQueryWrapper<CarWash>().eq(CarWash::getLicensePlateColor, 1).gt(CarWash::getCreateTime, startTime).eq(CarWash::getDeviceUuid, deviceUuid).orderByAsc(CarWash::getCreateTime).last(" LIMIT 15"));
            if (CollUtil.isNotEmpty(carWashList)){
                endTime = carWashList.getLast().getCreateTime();
            }
            if (CollUtil.isNotEmpty(carWashList)){
                String token = getToken(deviceUuid);
                if (token == null){//网络或接口异常，重试一次
                    token = getToken(deviceUuid);
                }
                if (token != null){
                    log.info("==========推送无锡地铁车冲信息开始：{}， 项目编号: {}====================", TimeUtil.format(LocalDateTime.now()), deviceMap.get(deviceUuid));
                    List<WuxiCarWashInfo> washList = new CopyOnWriteArrayList<>();
                    carWashList.parallelStream().forEach(carWash -> {
                        WuxiCarWashInfo washInfo = new WuxiCarWashInfo();
                        washInfo.setAccessTime(carWash.getWashTime());
                        washInfo.setCarNo(carWash.getLicensePlateNum());
                        if (StrUtil.isNotEmpty(carWash.getImages())) {
                            String[] images = carWash.getImages().split(",");
                            try(HttpResponse response = HttpRequest.head(images[0])
                                    .timeout(5000) // 设置超时时间5秒
                                    .execute()){
                                if (response.isOk()){
                                    washInfo.setPhoto(ImageUtil.compressImageSizeToBase64(images[0], 0.05f));
                                    washInfo.setBackPhoto(ImageUtil.compressImageSizeToBase64(images[images.length - 1], 0.05f));
                                }
                            } catch (Exception e){
                                return;
                        }
                            washInfo.setColor(colorMap.get(carWash.getLicensePlateColor()));
                            washInfo.setAbnormalSituation(eventMap.get(carWash.getEvent()));
                            washList.add(washInfo);
                        }
                    });
                    JSONObject pushInfo = new JSONObject();
                    pushInfo.put("itemId", deviceMap.get(deviceUuid));
                    pushInfo.put("washList", washList);

                    boolean success = false;
                    String responseBody;
                    try (HttpResponse response = HttpRequest.post(baseURL + "/equipment/externalAPi/pushCarWashAccess")
                            .header("Content-Type", "application/json") // 明确设置JSON类型
                            .header("Authorization", token)
                            .body(pushInfo.toJSONString())  // 传入JSON字符串
                            .execute()) {
                        if (response.isOk()){
                            success = true;
                            log.info("==========推送无锡地铁车冲返回：{}， 项目编号: {}====================", JSONObject.parseObject(response.body()).toJSONString(), deviceMap.get(deviceUuid));
                        } else {//未正常结束记录下deviceUuid,不更新缓存
                            deviceUuids.remove(deviceUuid);
                        }
                        responseBody = response.body();
                    }

                    //推送日志
                    for (CarWash carWash : carWashList){
                        CarWashPushLog pushLog = new CarWashPushLog();
                        pushLog.setDeviceUuid(deviceUuid);
                        try {
                            pushLog.setCarWashTime(TimeUtil.parseLocalDateTime(carWash.getWashTime()));
                        } catch (Exception e){
                            pushLog.setCarWashTime(null);
                        }
                        pushLog.setParams(JSONObject.toJSONString(carWash));
                        pushLog.setCreateTime(LocalDateTime.now());
                        pushLog.setSuccess(success);
                        pushLog.setReponse(responseBody);
                        carWashPushLogService.save(pushLog);
                    }
                }
            }
            redisUtil.set(RedisKeyEnum.LAST_CAR_WASH_PUSH_TIME.getKey() + deviceUuid, TimeUtil.format(endTime));
            log.info("==========推送无锡地铁车冲信息结束：{}， 项目编号: {}====================", TimeUtil.format(LocalDateTime.now()), deviceMap.get(deviceUuid));
        }
    }

    private String getToken(String deviceUuid){
        JSONObject pushInfo = new JSONObject();
        pushInfo.put("key", keyMap.get(deviceUuid));
        pushInfo.put("secret", secretMap.get(deviceUuid));
        try (HttpResponse response = HttpRequest.post(baseURL + "/auth/externalAPi/getToken")
                .header("Content-Type", "application/json") // 明确设置JSON类型
                .body(pushInfo.toJSONString())  // 传入JSON字符串
                .execute()) {
            if (response.isOk()){
                return JSONObject.parseObject(response.body()).getJSONObject("data").getString("token");
            }
        }
        return null;
    }

    @Getter
    @Setter
    @ToString
    public class WuxiCarWashInfo {

        //出入时间
        private String accessTime;

        //车牌号
        private String carNo;

        //照片
        private String photo;

        //车后照片
        private String backPhoto;

        //车牌颜色
        private String color;

        //异常情况 0 正常冲洗 1 冲洗时长不足 2 未出水 3 绕行
        private Integer abnormalSituation;
    }
}
